package com.admin.haitao.fragment

import android.annotation.SuppressLint
import android.os.Build
import android.os.Handler
import android.support.annotation.RequiresApi
import android.view.Gravity
import android.widget.Toast
import com.admin.haitao.R
import com.admin.haitao.activity.InfoDetailActivity
import com.admin.haitao.adapter.InfoAdapter
import com.admin.haitao.adapter.TypeAdapter
import com.admin.haitao.table.InfoDetail
import com.admin.haitao.table.Result
import com.admin.haitao.table.Type
import com.admin.kotlintest.utils.GsonUtils
import kotlinx.android.synthetic.main.fragment_home_pager.view.*
import kotlinx.android.synthetic.main.layout_title.view.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.support.v4.drawerListener

/**
 * Created by 吴昶 on 2018/8/16.
 */
abstract class HtAndHomeFragment:BaseFragment(){

    var data=ArrayList<InfoDetail>()
    var adapter: InfoAdapter?=null
    var url="https://guangdiu.com/api/getlist.php"
    var urlConnection=""
    var types=ArrayList<Type>()
    var typeAdapter: TypeAdapter?=null
    var isChecked = false

    var handler= Handler(Handler.Callback {
        when(it.what){
            0->{
                val result=it!!.obj as Result
                data.clear()
                data.addAll(result.data!!)
                adapter!!.upData(data)
                recordEId(data[data.size - 1].id)
                recordFId(data[0].id)
                fview!!.srl_fresh.finishRefresh()
            }
            1->{
                val result=it!!.obj as Result
                data.addAll(result.data!!)
                adapter!!.upData(data)
                recordEId(data[data.size - 1].id)
                fview!!.srl_fresh.finishLoadMore()
                Toast.makeText(activity,"又为您加载了"+result.data!!.size+"条", Toast.LENGTH_SHORT).show()
            }
        }
        false
    })


    override fun bindLayout(): Int {
        return R.layout.fragment_home_pager
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initData() {
        fview!!.line_bar.setBackgroundColor(resources.getColor(themeColor(),null))
        adapter=InfoAdapter(activity,R.layout.layout_info_item,data)
        fview!!.lv_list.adapter = adapter
        fview!!.srl_fresh.setOnRefreshListener {
            getData()
        }
        fview!!.srl_fresh.setPrimaryColorsId(themeColor(), android.R.color.white)
        fview!!.srl_fresh.setOnLoadMoreListener {
            loadMore()
        }
        //初始化获取数据
        getData()

        val str= GsonUtils.getJson(activity,assetsTypeData())
        types= GsonUtils.paresJsonArray(str,Type::class.java)
        typeAdapter=TypeAdapter(activity,R.layout.layout_type_item,types)
        fview!!.lv_types.adapter=typeAdapter
        initEvent()
    }

    /**
     * 第一条数据的 ID
     */
    abstract fun recordFId(cnf:Int)

    /**
     * 最后一条数据的 ID
     */
    abstract fun recordEId(cne:Int)

    /**
     * 获取数据
     */
    abstract fun getData()

    /**
     * 加载更多
     */
    abstract fun loadMore()

    /**
     * 主题颜色
     */
    abstract fun themeColor():Int
    /**
     * 获取配置文件的数据
     */
    abstract fun assetsTypeData():String

    @SuppressLint("SetTextI18n", "RtlHardcoded")
    private fun initEvent(){
        fview!!.lv_types.setOnItemClickListener { _, _, i, _ ->
            val item=types[i]
            if(item.type=="==") return@setOnItemClickListener
            when(item.type){
                "all"->{
                    urlConnection=""
                    fview!!.tv_type_title.text=""
                }
                "hot"->{
                    urlConnection="&onlyhots=1"
                    fview!!.tv_type_title.text=" - ${item.title}"
                }
                "mall"->{
                    urlConnection="&mall=${item.mall}"
                    fview!!.tv_type_title.text=" - 商城:${item.title}"
                }
                "cate"->{
                    urlConnection="&cate=${item.cate}"
                    fview!!.tv_type_title.text=" - 分类:${item.title}"
                }
            }
            typeAdapter!!.choseId=i
            typeAdapter!!.notifyDataSetChanged()
            //关闭侧边栏
            fview!!.dl_layout.closeDrawers()
            getData()
        }
        /**
         * 图标点击事件
         * 侧边栏切换
         */
        fview!!.iv_title_src.setOnClickListener {
            if(fview!!.dl_layout.isDrawerOpen(Gravity.LEFT)){
                fview!!.dl_layout.closeDrawers()
            }else{
                fview!!.dl_layout.openDrawer(Gravity.LEFT)
            }
        }

        /**
         * 侧边栏切换事件
         */
        fview!!.dl_layout.drawerListener {
            onDrawerStateChanged {
                if(it==2){
                    onTwitterClick()
                }
            }
        }

        fview!!.lv_list.setOnItemClickListener { _, _, i, _ ->
            val item=data[i]
            startActivity<InfoDetailActivity>( "item" to item)
        }
    }

    /**
     * 图标状态的修改
     */
    private fun onTwitterClick() {
        isChecked = !isChecked
        val stateSet = intArrayOf(android.R.attr.state_checked * if (isChecked) 1 else -1)
        fview!!.iv_title_src.setImageState(stateSet, true)
    }

    @SuppressLint("RtlHardcoded")
    override fun onPause() {
        super.onPause()
        if(fview!!.dl_layout.isDrawerOpen(Gravity.LEFT)){
            fview!!.dl_layout.closeDrawers()
        }
    }

}